package com.example.koizzi.ad20180517_news;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.koizzi.ad20180517_news.bean.Collect;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

//import cn.bmob.v3.BmobUser;

public class ViewNewsActivity extends AppCompatActivity {
    private static String newsUrl;//所观看的网址
    private static String newsUrl1;//所观看的网址
    static String tel;//获取前登录电话/id
    private WebView webView;
    private EditText edtComment;//获取评论
    private Button btnComment;//提交评论
    static boolean isCollect = true;
    static String objid ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_news);
        getNew1();
        initCommentViews();//评论
        InfoByBmobCollect();//获取收藏表信息
    }

    private void getNew1() {
        newsUrl = getIntent().getStringExtra("NEWS_URL");//新闻地址
        webView = findViewById(R.id.wv_news);
        webView.loadUrl(newsUrl);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    //查询收藏表，是否已经收藏------------------------------------------------------1
    private void InfoByBmobCollect() {
        //若未登录，不查询
        if(BmobUser.getCurrentUser() != null){
            BmobQuery<Collect> query = new BmobQuery<Collect>();
            query.addWhereEqualTo("UserID", tel);//搜索UserID==电话/账号
            query.setLimit(50);
            query.findObjects(new FindListener<Collect>() {
                @Override
                public void done(List<Collect> object, BmobException e) {
                    if(e==null && object.size()!=0){
                        for (Collect gameScore : object) {
                            if (gameScore.getUrlCollect().equals(newsUrl) && gameScore.getSaveOrDel()==true) {//已经收藏链接，且表里Boolean值为true
                                objid = gameScore.getObjectId();//获取ObjectId
                                isCollect = gameScore.getSaveOrDel();//已收藏，必定等于true
                            } else {//未收藏
                                isCollect = false;
                            }
                        }
                    }else{
                        Log.e("bmob","失败："+e.getMessage()+","+e.getErrorCode());
                    }
                }
            });
        }
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        //必须点击收藏星星后，才能开始判断，可能实际上没有用---------小bug------------2
        if (isCollect==true) {
            item.setIcon(R.drawable.star_full);
        } else {
            item.setIcon(R.drawable.star_empty);
        }
        switch (item.getItemId()) {
            //点击星星btn，监听------------------------------------------------------3
            case R.id.icon_collect:
                if(BmobUser.getCurrentUser() == null){//判断是否登录--------------3.1
                    toLoginActivity();//手机登录-----------------------------------3.2
//                    toLoginCountActivity();//账号密码登录-----暂时没用，节省短信
                }else {
                    //这里已经登录---------------------------------------------------4
                    if (isCollect==true){//从查询1的时候，已经判断赋值
                        isCollect = false;//点击后，取消收藏，图片改变
                        BmobQuery<Collect> query1 = new BmobQuery<Collect>();
                        query1.addWhereEqualTo("UserID", tel);//搜索UserID==电话/账号
                        query1.setLimit(50);
                        query1.findObjects(new FindListener<Collect>() {
                            @Override
                            public void done(List<Collect> object, BmobException e) {
                                Toast.makeText(ViewNewsActivity.this,"id为"+object.get(0).getObjectId(),Toast.LENGTH_SHORT).show();
                                DelCollect(object.get(0).getObjectId());
                            }
                        });
                        //删除该数据----------------------------5
                        item.setIcon(R.drawable.star_empty);
                    }else {//
                        isCollect = true;
//                        UpdateCollectBoolean(true);//
                        ToCollection();//收藏，保存数据---------------------------------6
                        item.setIcon(R.drawable.star_full);
                    }
                }
                break;
            case R.id.icon_setting:
                toLoginActivity();
                break;
            case R.id.icon_login:
                toLoginCountActivity();
                break;
            case R.id.icon_clist:
                //RecyView 收藏表 查看，删除网址 不做
                break;
            default:
        }
        return true;

    }
    //删除收藏数据--------------------------------------------------------------5
    private void DelCollect(String id) {
        if (id==null || id==""){
            Toast.makeText(ViewNewsActivity.this,"DelCollect---"+"id为空，请先登录",Toast.LENGTH_SHORT).show();
            return;
        }else {
            Collect p2 = new Collect();
            p2.setObjectId(id);
            p2.delete(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        Toast.makeText(ViewNewsActivity.this,"删除收藏成功",Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ViewNewsActivity.this,"删除收藏失败"+e.toString(),Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    //刷新boolean，刷新修改收藏信息-----
    private void UpdateCollectBoolean(boolean bs) {
        if (tel==null || tel==""){
            Toast.makeText(ViewNewsActivity.this,"UpdateCollect----"+"tel为空，请先登录",Toast.LENGTH_SHORT).show();
            return;
        }else {
            Collect gameScore = new Collect();
            gameScore.setSaveOrDel(bs);
            gameScore.setUserID(tel);
            gameScore.update(objid, new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if(e==null){
                        Log.i("bmob","更新成功");
                    }else{
                        Log.i("bmob","更新失败："+e.getMessage()+","+e.getErrorCode());
                    }
                }
            });
        }
    }
    //收藏，保存数据-----------UserID++Url++Boolean--------------------------------------------------6
    private void ToCollection() {
        if (tel==null || tel==""){
            Toast.makeText(ViewNewsActivity.this,"ToCollection---"+"tel为空，请先登录",Toast.LENGTH_SHORT).show();
            return;
        }else {
            Collect gameScore = new Collect();
            gameScore.setUserID(tel);
            if (newsUrl == null || newsUrl == "") {
                gameScore.setUrlCollect(newsUrl1);
            } else {
                gameScore.setUrlCollect(newsUrl);
            }
            gameScore.setSaveOrDel(true);
            gameScore.save(new SaveListener<String>() {
                @Override
                public void done(String objectId, BmobException e) {
                    if (e == null) {
                        Log.e("xxxxxxxxxxxx", "xx：收藏成功");
                    } else {
                        Log.e("yyyyyyyyyyyy", "yy：收藏失败");
                    }
                }
            });
        }
    }

    //手机登录--------------------------------------------------3
    private void toLoginActivity() {
        Intent toLogin = new Intent(ViewNewsActivity.this,LoginActivity.class);
        toLogin.putExtra("BBB" ,newsUrl);
        toLogin.putExtra("OBJ" ,objid);
        Toast.makeText(ViewNewsActivity.this,newsUrl1,Toast.LENGTH_SHORT).show();
        startActivity(toLogin);
    }
    //账号密码登录
    private void toLoginCountActivity() {
        Intent toLogin = new Intent(ViewNewsActivity.this,LoginCountActivity.class);
        toLogin.putExtra("CCC" ,newsUrl);
        Toast.makeText(ViewNewsActivity.this,newsUrl1,Toast.LENGTH_SHORT).show();
        startActivity(toLogin);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        refrashWebView();//登录后返回时刷新webView
    }

    private void refrashWebView() {
        newsUrl1 = getIntent().getStringExtra("NEWS_URL1");
        tel = getIntent().getStringExtra("TEL");
        objid = getIntent().getStringExtra("OBJID");
        webView.loadUrl(newsUrl1);
        Toast.makeText(ViewNewsActivity.this,"***"+newsUrl1,Toast.LENGTH_SHORT).show();
    }

    private void initCommentViews() {
        edtComment = findViewById(R.id.edt_comment);
        btnComment = findViewById(R.id.btn_comment);
        btnComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if(BmobUser.getCurrentUser() == null){
//                    Intent intent = new Intent();
//                    intent.setClass(ViewNewsActivity.this, LoginActivity.class);
//                    startActivity(intent);
//                }
                Toast.makeText(ViewNewsActivity.this,edtComment.getText().toString(),Toast.LENGTH_SHORT).show();
            }
        });
    }
}
